import SparkMD5 from 'spark-md5';

self.onmessage = function (e) {
    console.log(`开始计算文件md5`);
    const file = e.data.file;
    const chunkSize = e.data.chunkSize;
    const chunkNumber = e.data.chunkNumber;
    const chunks = [];
    const spark = new SparkMD5.ArrayBuffer();

    const calculateChunkMD5 = async (index) => {
        console.log(`计算分块${index}的md5`);
        
        if (index >= chunkNumber) {
            const md5 = spark.end();
            self.postMessage({ md5, chunks });
            return;
        }
        const start = index * chunkSize;
        const end = Math.min(start + chunkSize, file.size);
        const chunk = file.slice(start, end);

        const reader = new FileReader();
        await new Promise((resolve) => {
            reader.onload = (event) => {
                const buffer = event.target?.result;
                const chunkSpark = new SparkMD5.ArrayBuffer();
                chunkSpark.append(buffer);
                const chunkMD5 = chunkSpark.end();
                chunks.push({
                    file: chunk,
                    md5: chunkMD5
                });
                spark.append(buffer);
                resolve(null);
            };
            reader.readAsArrayBuffer(chunk);
        });
        calculateChunkMD5(index + 1);
    };

    calculateChunkMD5(0);
};

export default self;